package com.ycz.algorithm.utils.iteration;

/**
 * @author yancz
 * @ClassName IterationUtil
 * @description: 迭代：一种重复执行某个任务的控制结构。
 * @date 2024-08-27 15:03:18
 * @version: 1.0
 */
public class IterationUtil {

    /*
     * @author yancz
     * @description // for循环迭代
     * @date 2024/8/27 15:07
     * @param n
     * @return int
     **/
    public static int forLoop(int n) {
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res += i;
        }
        return res;
    }

    /*
     * @author yancz
     * @description // while循环迭代，自由度更高
     * @date 2024/8/27 15:17
     * @param n
     * @return int
     **/
    public static int whileLoop(int n) {
        int res = 0, i = 1;
        while (i <= n) {
            res += i;
            i++;
            i *= 2;
        }
        return res;
    }

    /*
     * @author yancz
     * @description // 嵌套循环，算法运行时间与输入的数据大小成平方关系，每增加一层嵌套，运行时间都是一次生升维
     * @date 2024/8/27 15:31
     * @param n
     * @return String
     **/
    public static String nestedLoop(int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                sb.append("(").append(i).append(", ").append(j).append("), ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(forLoop(20));
        System.out.println(whileLoop(100));
        System.out.println(nestedLoop(5));
    }

}
